package part01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class FlinkDemo {
    public static void main(String[] args) throws Exception {
        //1，获取flink Stream执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //2，读取数据源
        DataStreamSource<String> data = env.readTextFile("D:\\Java\\flink\\input\\hello.txt");
        //3，处理数据,flatMap切分数据，keyBy分组，sum计数
        SingleOutputStreamOperator<Tuple2<String, Long>> outData = data.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] split = s.split("\\s+");
                for (String word : split) {
                    collector.collect(Tuple2.of(word, 1L));
                }
            }
        }).keyBy(0)
                .sum(1);
        //4，输出处理数据到控制台
        outData.print();
        //5，触发执行
        env.execute();
    }
}
